/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.dao.jpa;

import com.jmooc.dao.CourseDao;
import com.jmooc.entity.Course;
import com.jmooc.entity.CourseModule;
import com.jmooc.entity.Course_;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Group
 */
@Stateless
public class JpaCourseDao implements CourseDao {
    
    @PersistenceContext
    private EntityManager em;
    
    @Override
    public List<Course> getAllCourses() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Course> cq = cb.createQuery(Course.class);
        Root<Course> trainStation = cq.from(Course.class);
        cq.select(trainStation);
        return em.createQuery(cq).getResultList();
        //return em.createQuery("SELECT c FROM Course c").getResultList();
    }

    @Override
    public void create(Course course) {
        em.persist(course);
    }

    @Override
    public Course getById(Long id) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Course> query = cb.createQuery(Course.class);
        Root<Course> user = query.from(Course.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(Course_.id), id)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getSingleResult();
        //return (Course) em.createQuery("SELECT c FROM Course c WHERE c.id = :d").setParameter("d", id).getSingleResult();
    }

    @Override
    public Course getByCourseModule(CourseModule courseModule) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Course> query = cb.createQuery(Course.class);
        Root<Course> user = query.from(Course.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(Course_.courseModules), courseModule)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getSingleResult();
        //return (Course) em.createQuery("SELECT c FROM Course c LEFT JOIN c.courseModules cm WHERE cm.id :c").setParameter("c", courseModule.getId());
    }

}
